<template>
  <div v-loading="loading">
    <table class="table table-bordered mt-3 mb-1">
      <tbody>
        <tr>
          <td colspan="10" class="font-weight-bold" data-font-bold="true">
            资金来源
            <el-button type="text" v-if="!isViewMode" class="py-0" @click="handlerEdit">
              <i class="fa fa-edit"></i>
            </el-button>
          </td>
        </tr>
        <tr>
          <td colspan="2" width="25%">名称</td>
          <td colspan="2" width="18%">金额(万元)</td>
          <td colspan="3" width="27%">资金用途</td>
          <td colspan="3" width="30%">备注</td>
        </tr>
        <tr v-if="!finances.length">
          <td colspan="2">-</td>
          <td colspan="2">-</td>
          <td colspan="3">-</td>
          <td colspan="3">-</td>
        </tr>
        <tr v-for="(item, index) in finances" :key="index">
          <td colspan="2">{{ item.capital_source || '-' }}</td>
          <td colspan="2">{{ item.funds || '-' }}</td>
          <td colspan="3">{{ item.capital_use || '-' }}</td>
          <td class="p-0" colspan="3">{{ item.remark || '-' }}</td>
        </tr>
      </tbody>
    </table>

    <el-dialog
      :visible.sync="visible"
      :close-on-click-modal="false"
      append-to-body
      title="修改资金来源信息"
      width="1000px"
    >
      <table class="table table-bordered mt-3 mb-1">
        <tbody>
          <tr>
            <td colspan="2" width="25%">名称</td>
            <td colspan="2" width="18%">金额(万元)</td>
            <td colspan="3" width="27%">资金用途</td>
            <td colspan="3" width="30%">备注</td>
          </tr>
          <tr v-for="(p, index) of editData" :key="index">
            <td class="report-input-td" colspan="2">
              <c-select
                allow-create
                default-first-option
                clearable
                filterable
                v-model="p.capital_source_key"
                class="w-100"
                placeholder="选择项目或填写名称"
                :options="enumFinanceSourceType"
                @change="key => onFinaceChange(key, p)"
              ></c-select>
            </td>
            <td class="report-input-td" colspan="2">
              <el-input
                v-model="p.funds"
                class="text-center"
                placeholder="输入金额"
                type="number"
              ></el-input>
            </td>
            <td class="report-input-td" colspan="3">
              <el-input
                v-model="p.capital_use"
                class="text-center"
                placeholder="输入资金用途"
              ></el-input>
            </td>
            <td class="report-input-td" colspan="3">
              <div class="d-flex align-items-center">
                <div class="flex-1 px-1">
                  <el-input
                    v-model="p.remark"
                    class="text-center flex"
                    placeholder="备注"
                  ></el-input>
                </div>
                <el-button
                  class="td-inner-btn px-3 text-danger"
                  type="text"
                  @click="deleteData(p.id, index)"
                >
                  <i class="fa fa-trash"></i>
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <el-button-group class="mb-2 mt-1">
        <el-button size="small" @click="editRowAdd">
          <i class="fa fa-indent"></i>
          添加一行
        </el-button>
      </el-button-group>
      <div class="text-center">
        <el-button type="primary" @click="saveData" :loading="saveLoading" style="min-width: 100px">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { enumFinanceSourceType } from '@/credit/plugins/enum'
import { getResultArray } from '@/gov/components/creditFile/index'
export default {
  components: {},
  props: {
    queryId: {
      type: String,
      default: '',
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumFinanceSourceType,
      loading: false,
      visible: false,
      saveLoading: false,
      tableName: 'datum_customer_finance_capital_source',
      finances: [],
      editData: [],
    }
  },
  computed: {
    isViewMode() {
      return this.viewMode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        if (!this.queryId) {
          return
        }
        this.getData()
      },
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    onFinaceChange(key, p) {
      p.capital_source = this.enumFinanceSourceType[key] || key
    },
    getData() {
      this.loading = true
      const params = { 'customer_related_id.eq': this.queryId }
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          this.finances = getResultArray(res)
          this.editData = this.finances.map(item => {
            return { ...item }
          })
          if (this.editData.length < 5) {
            this.addTemp(5 - this.editData.length)
          }
        })
        .catch(res => {
          this.$message.error(`请求资金来源信息失败${res}`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handlerEdit() {
      this.editData = []
      this.visible = true
      this.editData = this.finances.map(item => {
        return { ...item }
      })
      if (this.editData.length < 5) {
        this.addTemp(5 - this.editData.length)
      }
    },
    addTemp(len) {
      for (let i = 0; i < len; i++) {
        this.editData.push({})
      }
    },
    editRowAdd() {
      this.addTemp(1)
    },
    deleteItem(index) {
      this.editData.splice(index, 1)
    },
    saveData() {
      let data = []
      for (let item of this.editData) {
        if (item.id && !item.capital_source_key) {
          return this.$message.warning('请选择或填写资金来源')
        }
        if (item.capital_source_key) {
          item.customer_related_id = this.queryId
          data.push(item)
        }
      }
      if (!data.length) {
        return
      }
      this.saveLoading = true
      this.$api
        .updateBatch(this.$serviceName, this.tableName, data)
        .then(() => {
          this.$message.success('保存成功')
          this.getData()
          this.visible = false
        })
        .catch(() => {
          this.$message.error('保存失败')
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    deleteData(id, index) {
      if (!id) {
        this.deleteItem(index)
        return
      }
      this.$utils
        .msgbox({
          message: '确定删除?',
          beforeClose: () => this.$api.deleteData(this.$serviceName, this.tableName, id),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/gov/components/creditFile/style.scss';
</style>
